import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 游戏配置
const GAME_CONFIG = {
    SAVE_KEY: 'virtual_pet_save',
    MAX_LEVEL: 150,
    BASE_EXP: 150,
    EXP_GROWTH: 1.2,
    STAT_DECAY: {
        HUNGER: 1.2,      // 每分钟降低值
        HAPPINESS: 0.8,
        ENERGY: -0.8    // 负值表示恢复
    },
    REWARDS: {
        LEVEL_UP: level => level * 150,
        ACHIEVEMENT: 300,
        DAILY_LOGIN: 100
    },
    PRICES: {
        FOOD: {
            BASIC: 75,
            PREMIUM: 175,
            DELUXE: 375
        },
        TOY: {
            BASIC: 175,
            PREMIUM: 375,
            DELUXE: 675
        }
    },
    EFFECTS: {
        FOOD: {
            BASIC: { hunger: 30, happiness: 10 },
            PREMIUM: { hunger: 60, happiness: 20 },
            DELUXE: { hunger: 120, happiness: 40 }
        },
        TOY: {
            BASIC: { happiness: 30, energy: -15 },
            PREMIUM: { happiness: 60, energy: -30 },
            DELUXE: { happiness: 120, energy: -60 }
        }
    }
}

// 商品数据
const foodItems = [
    {
        id: 'milk_bottle',
        name: '温暖牛奶',
        description: '香甜可口的温牛奶，能让宠物感到温暖和满足',
        price: 50,
        image: '/static/items/milk.svg',
        effect: {
            hunger: 15,
            happiness: 5
        }
    },
    {
        id: 'premium_cat_food',
        name: '高级猫粮',
        description: '营养均衡的顶级猫粮，添加了特殊营养成分',
        price: 100,
        image: '/static/items/cat_food.svg',
        effect: {
            hunger: 30,
            happiness: 10
        }
    },
    {
        id: 'tuna_can',
        name: '金枪鱼罐头',
        description: '新鲜美味的金枪鱼，宠物的最爱',
        price: 150,
        image: '/static/items/tuna.svg',
        effect: {
            hunger: 40,
            happiness: 15
        }
    },
    {
        id: 'salmon_sushi',
        name: '三文鱼寿司',
        description: '精致的三文鱼寿司，奢华的美食体验',
        price: 200,
        image: '/static/items/sushi.svg',
        effect: {
            hunger: 50,
            happiness: 20
        }
    }
];

const toyItems = [
    {
        id: 'yarn_ball',
        name: '毛线球',
        description: '柔软的毛线球，适合追逐和玩耍',
        price: 30,
        image: '/static/items/yarn.svg',
        effect: {
            happiness: 10,
            energy: -5
        }
    },
    {
        id: 'laser_pointer',
        name: '激光笔',
        description: '会发出红点的激光笔，让宠物追逐光点',
        price: 80,
        image: '/static/items/laser.svg',
        effect: {
            happiness: 20,
            energy: -10
        }
    },
    {
        id: 'cat_tower',
        name: '猫爬架',
        description: '多层的猫爬架，可以攀爬和休息',
        price: 300,
        image: '/static/items/tower.svg',
        effect: {
            happiness: 30,
            energy: -15
        }
    },
    {
        id: 'interactive_robot',
        name: '智能玩具',
        description: '能自动移动的智能玩具，带来持续的乐趣',
        price: 500,
        image: '/static/items/robot.svg',
        effect: {
            happiness: 40,
            energy: -20
        }
    }
];

export { foodItems, toyItems };

// 初始状态
const initialState = {
    pet: {
        name: '1号黑奴',
        level: 1,
        exp: 0,
        expToNextLevel: 100,
        hunger: 50,
        happiness: 50,
        energy: 100,
        stats: {
            feedCount: 0,
            playCount: 0,
            sleepCount: 0,
            totalInteractions: 0,
            gameStartTime: Date.now()
        },
        achievements: {
            'ACHIEVEMENT_FEEDER': {
                id: 'ACHIEVEMENT_FEEDER',
                name: '美食家',
                description: '喂食10次',
                progress: 0,
                completed: false,
                reward: 100, // 成就奖励金币
                claimed: false
            },
            'ACHIEVEMENT_MASTER_FEEDER': {
                id: 'ACHIEVEMENT_MASTER_FEEDER',
                name: '美食大师',
                description: '喂食50次',
                progress: 0,
                completed: false,
                reward: 500,
                claimed: false
            },
            'ACHIEVEMENT_PLAYER': {
                id: 'ACHIEVEMENT_PLAYER',
                name: '玩乐达人',
                description: '玩耍10次',
                progress: 0,
                completed: false,
                reward: 100,
                claimed: false
            },
            'ACHIEVEMENT_MASTER_PLAYER': {
                id: 'ACHIEVEMENT_MASTER_PLAYER',
                name: '欢乐大师',
                description: '玩耍50次',
                progress: 0,
                completed: false,
                reward: 500,
                claimed: false
            },
            'ACHIEVEMENT_SLEEPER': {
                id: 'ACHIEVEMENT_SLEEPER',
                name: '睡神',
                description: '休息10次',
                progress: 0,
                completed: false,
                reward: 100,
                claimed: false
            }
        }
    },
    inventory: {
        coins: 500,
        items: []
    },
    shopItems: {
        food: foodItems,
        toys: toyItems
    },
    gameState: {
        settings: {
            bgm: true,
            sfx: true,
            notifications: true,
            autoSave: true
        },
        currentEvent: null,
        lastSaveTime: null
    }
}

const store = new Vuex.Store({
    state: JSON.parse(JSON.stringify(initialState)), // Deep copy to avoid reference issues

    mutations: {
        loadGame(state) {
            const savedData = uni.getStorageSync(GAME_CONFIG.SAVE_KEY)
            if (savedData && savedData.pet) {
                // 确保所有必要的属性都存在
                state.pet = {
                    ...state.pet, // 保持默认值
                    ...savedData.pet, // 加载保存的数据
                    stats: {
                        ...state.pet.stats, // 默认统计数据
                        ...savedData.pet.stats // 保存的统计数据
                    },
                    achievements: {
                        ...state.pet.achievements, // 默认成就数据
                        ...savedData.pet.achievements // 保存的成就数据
                    }
                }
                
                // 重新计算所有成就进度
                const stats = state.pet.stats
                const achievements = state.pet.achievements
                
                // 喂食成就
                if (stats.feedCount) {
                    achievements['ACHIEVEMENT_FEEDER'].progress = Math.min((stats.feedCount / 10) * 100, 100)
                    achievements['ACHIEVEMENT_FEEDER'].completed = achievements['ACHIEVEMENT_FEEDER'].progress >= 100
                    
                    achievements['ACHIEVEMENT_MASTER_FEEDER'].progress = Math.min((stats.feedCount / 50) * 100, 100)
                    achievements['ACHIEVEMENT_MASTER_FEEDER'].completed = achievements['ACHIEVEMENT_MASTER_FEEDER'].progress >= 100
                }
                
                // 玩耍成就
                if (stats.playCount) {
                    achievements['ACHIEVEMENT_PLAYER'].progress = Math.min((stats.playCount / 10) * 100, 100)
                    achievements['ACHIEVEMENT_PLAYER'].completed = achievements['ACHIEVEMENT_PLAYER'].progress >= 100
                    
                    achievements['ACHIEVEMENT_MASTER_PLAYER'].progress = Math.min((stats.playCount / 50) * 100, 100)
                    achievements['ACHIEVEMENT_MASTER_PLAYER'].completed = achievements['ACHIEVEMENT_MASTER_PLAYER'].progress >= 100
                }
                
                // 睡眠成就
                if (stats.sleepCount) {
                    achievements['ACHIEVEMENT_SLEEPER'].progress = Math.min((stats.sleepCount / 10) * 100, 100)
                    achievements['ACHIEVEMENT_SLEEPER'].completed = achievements['ACHIEVEMENT_SLEEPER'].progress >= 100
                }
            }
        },

        initializeGame(state, savedData) {
            if (savedData) {
                Object.assign(state, savedData)
            }
            state.gameState.settings = {
                bgm: true,
                sfx: true,
                notifications: true,
                autoSave: true
            }
            state.gameState.lastSaveTime = Date.now()
            // 初始化后保存
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
        },

        setPet(state, pet) {
            state.pet = { ...state.pet, ...pet }
        },

        updatePetStatus(state, { key, value }) {
            // 支持嵌套属性路径，如 'stats.feedCount'
            const keys = key.split('.')
            let target = state.pet
            
            // 遍历到倒数第二层
            for (let i = 0; i < keys.length - 1; i++) {
                if (!target[keys[i]]) {
                    target[keys[i]] = {}
                }
                target = target[keys[i]]
            }
            
            // 设置最后一层的值
            const lastKey = keys[keys.length - 1]
            if (['hunger', 'happiness', 'energy'].includes(lastKey)) {
                target[lastKey] = Math.max(0, Math.min(value, 100))
            } else {
                target[lastKey] = value
            }
            
            // 保存状态
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
        },

        addExp(state, amount) {
            state.pet.exp += amount
            // 检查是否可以升级
            while (state.pet.exp >= state.pet.expToNextLevel && state.pet.level < GAME_CONFIG.MAX_LEVEL) {
                // 升级
                state.pet.level++
                // 记录剩余经验值
                state.pet.exp -= state.pet.expToNextLevel
                // 计算下一级所需经验值（随等级增加而增加）
                state.pet.expToNextLevel = Math.floor(GAME_CONFIG.BASE_EXP * Math.pow(GAME_CONFIG.EXP_GROWTH, state.pet.level - 1))
                
                // 升级奖励：恢复所有状态
                state.pet.hunger = 100
                state.pet.happiness = 100
                state.pet.energy = 100
            }
            // 如果已达到最大等级，经验值保持在0
            if (state.pet.level >= GAME_CONFIG.MAX_LEVEL) {
                state.pet.exp = 0
            }
            // 自动保存
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
        },

        updateAchievementProgress(state, { id, progress }) {
          if (state.pet.achievements[id]) {
            state.pet.achievements[id].progress = Math.min(100, progress)
            if (progress >= 100 && !state.pet.achievements[id].completed) {
              state.pet.achievements[id].completed = true
              // 触发成就完成事件
              state.gameState.currentEvent = {
                type: 'ACHIEVEMENT',
                message: `恭喜解锁新成就！`,
                duration: 3000
              }
            }
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
          }
        },

        claimAchievementReward(state, achievementId) {
            const achievement = state.pet.achievements[achievementId]
            if (achievement && achievement.completed && !achievement.claimed) {
                state.inventory.coins = (state.inventory.coins || 0) + achievement.reward
                achievement.claimed = true
                uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
            }
        },

        updateCoins(state, amount) {
            state.inventory.coins = Math.max(0, (state.inventory.coins || 0) + amount)
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
        },

        updateSettings(state, settings) {
            state.gameState.settings = { ...state.gameState.settings, ...settings }
        },

        updateLastSaveTime(state) {
            state.gameState.lastSaveTime = Date.now()
        },

        // 基础的状态修改函数
        updateHunger(state, value) {
            state.pet.hunger = Math.max(0, Math.min(120, state.pet.hunger + value))
        },

        updateHappiness(state, value) {
            state.pet.happiness = Math.max(0, Math.min(120, state.pet.happiness + value))
        },

        updateEnergy(state, value) {
            state.pet.energy = Math.max(0, Math.min(120, state.pet.energy + value))
        },

        updateGameTime(state) {
            if (!state.pet.stats.lastLoginTime) {
                state.pet.stats.lastLoginTime = Date.now()
            }
            const now = Date.now()
            const timeDiff = now - state.pet.stats.lastLoginTime
            const minutesPlayed = Math.floor(timeDiff / 60000)
            state.pet.stats.totalPlayTime = (state.pet.stats.totalPlayTime || 0) + minutesPlayed
            state.pet.stats.lastLoginTime = now
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
        },
        
        incrementInteractions(state) {
            state.pet.stats.interactions = (state.pet.stats.interactions || 0) + 1
            uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
        },
        
        updatePetStatus(state, { key, value }) {
            state.pet[key] = value
        },
        
        updatePetStats(state, { key, value }) {
            state.pet.stats[key] = value
        },
        
        updateCoins(state, value) {
            state.inventory.coins = value
        },
        
        addToInventory(state, { type, item }) {
            state.inventory.items.push({
                ...item,
                type,
                id: Date.now()
            })
        },
        
        useItem(state, itemId) {
            const itemIndex = state.inventory.items.findIndex(item => item.id === itemId)
            if (itemIndex > -1) {
                const item = state.inventory.items[itemIndex]
                
                // 应用物品效果
                if (item.type === 'food') {
                    if (item.effect.hunger) {
                        state.pet.hunger = Math.min(100, state.pet.hunger + item.effect.hunger)
                    }
                    state.pet.stats.feedCount++
                }
                
                if (item.effect.happiness) {
                    state.pet.happiness = Math.min(100, state.pet.happiness + item.effect.happiness)
                }
                
                if (item.type === 'toys') {
                    if (item.effect.energy) {
                        state.pet.energy = Math.max(0, state.pet.energy + item.effect.energy)
                    }
                    state.pet.stats.playCount++
                }
                
                // 从背包中移除物品
                state.inventory.items.splice(itemIndex, 1)
            }
        }
    },

    actions: {
        initGame({ commit }) {
            try {
                // 尝试从本地存储加载数据
                const savedData = uni.getStorageSync(GAME_CONFIG.SAVE_KEY)
                if (savedData) {
                    commit('loadGame')
                } else {
                    // 如果没有存储数据，初始化新游戏
                    const initialState = {
                        pet: {
                            name: '1号黑奴',
                            level: 1,
                            exp: 0,
                            expToNextLevel: 100,
                            hunger: 50,
                            happiness: 50,
                            energy: 100,
                            stats: {
                                feedCount: 0,
                                playCount: 0,
                                sleepCount: 0,
                                totalInteractions: 0,
                                gameStartTime: Date.now()
                            },
                            achievements: {
                                'ACHIEVEMENT_FEEDER': {
                                    id: 'ACHIEVEMENT_FEEDER',
                                    name: '美食家',
                                    description: '喂食10次',
                                    progress: 0,
                                    completed: false,
                                    reward: 100,
                                    claimed: false
                                },
                                'ACHIEVEMENT_MASTER_FEEDER': {
                                    id: 'ACHIEVEMENT_MASTER_FEEDER',
                                    name: '美食大师',
                                    description: '喂食50次',
                                    progress: 0,
                                    completed: false,
                                    reward: 500,
                                    claimed: false
                                },
                                'ACHIEVEMENT_PLAYER': {
                                    id: 'ACHIEVEMENT_PLAYER',
                                    name: '玩乐达人',
                                    description: '玩耍10次',
                                    progress: 0,
                                    completed: false,
                                    reward: 100,
                                    claimed: false
                                },
                                'ACHIEVEMENT_MASTER_PLAYER': {
                                    id: 'ACHIEVEMENT_MASTER_PLAYER',
                                    name: '欢乐大师',
                                    description: '玩耍50次',
                                    progress: 0,
                                    completed: false,
                                    reward: 500,
                                    claimed: false
                                },
                                'ACHIEVEMENT_SLEEPER': {
                                    id: 'ACHIEVEMENT_SLEEPER',
                                    name: '睡神',
                                    description: '休息10次',
                                    progress: 0,
                                    completed: false,
                                    reward: 100,
                                    claimed: false
                                }
                            }
                        },
                        inventory: {
                            coins: 500,
                            items: []
                        },
                        shopItems: {
                            food: foodItems,
                            toys: toyItems
                        },
                        gameState: {
                            settings: {
                                bgm: true,
                                sfx: true,
                                notifications: true,
                                autoSave: true
                            },
                            currentEvent: null,
                            lastSaveTime: null
                        }
                    }
                    commit('initializeGame', initialState)
                }
                
                // 开始游戏循环
                commit('updateGameTime')
                setInterval(() => {
                    commit('updateGameTime')
                }, 60000) // 每分钟更新一次游戏时间
                
            } catch (error) {
                console.error('Failed to load game data:', error)
                commit('initializeGame')
            }
        },

        saveGame({ state }) {
            try {
                uni.setStorageSync(GAME_CONFIG.SAVE_KEY, state)
                console.log('Game saved successfully')
            } catch (error) {
                console.error('Failed to save game:', error)
            }
        },

        // 定期自动保存
        startAutoSave({ dispatch }) {
            setInterval(() => {
                dispatch('saveGame')
            }, 60000) // 每分钟自动保存一次
        },

        resetGame({ commit }) {
            localStorage.removeItem(GAME_CONFIG.SAVE_KEY)
            commit('initializeGame', null)
        },

        startGameLoop({ state, commit, dispatch }) {
            setInterval(() => {
                // 更新状态
                Object.entries(GAME_CONFIG.STAT_DECAY).forEach(([stat, value]) => {
                    const currentValue = state.pet[stat.toLowerCase()]
                    const newValue = Math.max(0, Math.min(120, currentValue - value))
                    commit('updatePetStatus', {
                        key: stat.toLowerCase(),
                        value: newValue
                    })
                })

                // 自动保存
                if (state.gameState.settings.autoSave) {
                    dispatch('saveGame')
                }

            }, 60000) // 每分钟更新一次
        },

        checkDailyLogin({ state, commit }) {
            const today = new Date().toDateString()
            if (state.pet.lastLoginDate !== today) {
                commit('updateCoins', GAME_CONFIG.REWARDS.DAILY_LOGIN)
                commit('setPet', { lastLoginDate: today })
                commit('setEvent', {
                    type: 'DAILY_LOGIN',
                    message: `欢迎回来！获得${GAME_CONFIG.REWARDS.DAILY_LOGIN}金币的每日登录奖励！`,
                    duration: 3000
                })
            }
        },

        checkAchievements({ state, commit }) {
          // 检查喂食成就
          const feedProgress = (state.pet.stats.feedCount / 10) * 100
          commit('updateAchievementProgress', { 
            id: 'ACHIEVEMENT_FEEDER', 
            progress: feedProgress 
          })
          
          const masterFeedProgress = (state.pet.stats.feedCount / 50) * 100
          commit('updateAchievementProgress', { 
            id: 'ACHIEVEMENT_MASTER_FEEDER', 
            progress: masterFeedProgress 
          })

          // 检查玩耍成就
          const playProgress = (state.pet.stats.playCount / 10) * 100
          commit('updateAchievementProgress', { 
            id: 'ACHIEVEMENT_PLAYER', 
            progress: playProgress 
          })
          
          const masterPlayProgress = (state.pet.stats.playCount / 50) * 100
          commit('updateAchievementProgress', { 
            id: 'ACHIEVEMENT_MASTER_PLAYER', 
            progress: masterPlayProgress 
          })

          // 检查休息成就
          const sleepProgress = (state.pet.stats.sleepCount / 10) * 100
          commit('updateAchievementProgress', { 
            id: 'ACHIEVEMENT_SLEEPER', 
            progress: sleepProgress 
          })

          // 检查等级成就
          const levelProgress = (state.pet.level / 10) * 100
          commit('updateAchievementProgress', { 
            id: 'ACHIEVEMENT_HIGH_LEVEL', 
            progress: levelProgress 
          })
        },

        async feedPet({ commit, state, dispatch }, foodType = 'BASIC') {
            if (!state.pet || state.pet.hunger >= 100) return false

            const effect = GAME_CONFIG.EFFECTS.FOOD[foodType]
            if (!effect) return false

            // 更新饥饿度和心情
            const newHunger = Math.min(state.pet.hunger + effect.hunger, 100)
            const newHappiness = Math.min(state.pet.happiness + effect.happiness, 100)

            commit('updatePetStatus', { key: 'hunger', value: newHunger })
            commit('updatePetStatus', { key: 'happiness', value: newHappiness })
            
            // 更新互动统计
            const currentFeedCount = state.pet.stats?.feedCount || 0
            const newFeedCount = currentFeedCount + 1
            
            commit('updatePetStatus', { key: 'stats.feedCount', value: newFeedCount })
            commit('incrementInteractions')
            
            // 更新成就进度
            const achievements = state.pet.achievements || {}
            
            // 美食家成就 (10次)
            const feederProgress = Math.min((newFeedCount / 10) * 100, 100)
            achievements['ACHIEVEMENT_FEEDER'] = {
                ...achievements['ACHIEVEMENT_FEEDER'],
                progress: feederProgress,
                completed: feederProgress >= 100
            }
            
            // 美食大师成就 (50次)
            const masterFeederProgress = Math.min((newFeedCount / 50) * 100, 100)
            achievements['ACHIEVEMENT_MASTER_FEEDER'] = {
                ...achievements['ACHIEVEMENT_MASTER_FEEDER'],
                progress: masterFeederProgress,
                completed: masterFeederProgress >= 100
            }
            
            commit('updatePetStatus', { key: 'achievements', value: achievements })
            
            // 添加经验值
            const expGain = Math.floor(15 * (1 + (state.pet.level - 1) * 0.1))
            commit('addExp', expGain)
            
            dispatch('saveGame')
            return true
        },

        async playWithPet({ commit, state, dispatch }, toyType = 'BASIC') {
            if (!state.pet || state.pet.energy <= 0) return false

            const effect = GAME_CONFIG.EFFECTS.TOY[toyType]
            if (!effect) return false

            // 更新心情和体力
            const newHappiness = Math.min(state.pet.happiness + effect.happiness, 100)
            const newEnergy = Math.max(0, state.pet.energy + effect.energy)

            commit('updatePetStatus', { key: 'happiness', value: newHappiness })
            commit('updatePetStatus', { key: 'energy', value: newEnergy })
            
            // 更新互动统计
            const currentPlayCount = state.pet.stats?.playCount || 0
            const newPlayCount = currentPlayCount + 1
            
            commit('updatePetStatus', { key: 'stats.playCount', value: newPlayCount })
            commit('incrementInteractions')
            
            // 更新成就进度
            const achievements = state.pet.achievements || {}
            
            // 玩乐达人成就 (10次)
            const playerProgress = Math.min((newPlayCount / 10) * 100, 100)
            achievements['ACHIEVEMENT_PLAYER'] = {
                ...achievements['ACHIEVEMENT_PLAYER'],
                progress: playerProgress,
                completed: playerProgress >= 100
            }
            
            // 欢乐大师成就 (50次)
            const masterPlayerProgress = Math.min((newPlayCount / 50) * 100, 100)
            achievements['ACHIEVEMENT_MASTER_PLAYER'] = {
                ...achievements['ACHIEVEMENT_MASTER_PLAYER'],
                progress: masterPlayerProgress,
                completed: masterPlayerProgress >= 100
            }
            
            commit('updatePetStatus', { key: 'achievements', value: achievements })

            // 添加经验值
            const expGain = Math.floor(10 * (1 + (state.pet.level - 1) * 0.1))
            commit('addExp', expGain)

            dispatch('saveGame')
            return true
        },

        async sleep({ commit, state, dispatch }) {
            if (!state.pet || state.pet.energy >= 100) return false

            // 更新体力和心情
            const energyGain = 50
            const happinessGain = 10
            
            const newEnergy = Math.min(state.pet.energy + energyGain, 100)
            const newHappiness = Math.min(state.pet.happiness + happinessGain, 100)

            commit('updatePetStatus', { key: 'energy', value: newEnergy })
            commit('updatePetStatus', { key: 'happiness', value: newHappiness })
            
            // 更新互动统计
            const currentSleepCount = state.pet.stats?.sleepCount || 0
            const newSleepCount = currentSleepCount + 1
            
            commit('updatePetStatus', { key: 'stats.sleepCount', value: newSleepCount })
            commit('incrementInteractions')
            
            // 更新成就进度
            const achievements = state.pet.achievements || {}
            
            // 睡神成就 (10次)
            const sleeperProgress = Math.min((newSleepCount / 10) * 100, 100)
            achievements['ACHIEVEMENT_SLEEPER'] = {
                ...achievements['ACHIEVEMENT_SLEEPER'],
                progress: sleeperProgress,
                completed: sleeperProgress >= 100
            }
            
            commit('updatePetStatus', { key: 'achievements', value: achievements })

            // 添加经验值
            const expGain = Math.floor(5 * (1 + (state.pet.level - 1) * 0.1))
            commit('addExp', expGain)

            dispatch('saveGame')
            return true
        }
    },

    getters: {
        petMood: state => {
            const { happiness, hunger, energy } = state.pet
            if (happiness >= 100 && hunger >= 80 && energy >= 80) return 'excellent'
            if (happiness >= 80) return 'happy'
            if (happiness >= 50) return 'normal'
            return 'sad'
        },

        petStatus: state => {
            const { hunger, happiness, energy } = state.pet
            return {
                hunger: {
                    value: hunger,
                    status: hunger >= 80 ? 'good' : hunger >= 40 ? 'warning' : 'danger',
                    text: hunger >= 80 ? '饱食' : hunger >= 40 ? '略饿' : '饥饿'
                },
                happiness: {
                    value: happiness,
                    status: happiness >= 80 ? 'good' : happiness >= 40 ? 'warning' : 'danger',
                    text: happiness >= 80 ? '开心' : happiness >= 40 ? '一般' : '不开心'
                },
                energy: {
                    value: energy,
                    status: energy >= 80 ? 'good' : energy >= 40 ? 'warning' : 'danger',
                    text: energy >= 80 ? '精力充沛' : energy >= 40 ? '有点累' : '疲惫'
                }
            }
        },

        canFeed: state => foodType => {
            return state.inventory.coins >= GAME_CONFIG.PRICES.FOOD[foodType] &&
                   state.pet.hunger < 100
        },

        canPlay: state => toyType => {
            const toy = GAME_CONFIG.EFFECTS.TOY[toyType]
            return state.inventory.coins >= GAME_CONFIG.PRICES.TOY[toyType] &&
                   state.pet.energy > Math.abs(toy.energy)
        },

        canSleep: state => {
            return state.pet.energy < 100
        },

        achievementProgress: state => {
          const achievements = state.pet.achievements
          const total = Object.keys(achievements).length
          const completed = Object.values(achievements).filter(a => a.completed).length
          return {
            total,
            completed,
            percentage: Math.round((completed / total) * 100)
          }
        },

        gameStats: state => {
            return {
                totalPlayTime: state.pet.stats.totalPlayTime,
                highestLevel: state.pet.stats.highestLevel,
                totalLevelUps: state.pet.stats.totalLevelUps,
                totalFeeds: state.pet.stats.totalFeeds,
                totalPlays: state.pet.stats.totalPlays,
                totalSleeps: state.pet.stats.totalSleeps
            }
        },

        shopItems: state => {
            return {
                food: state.shopItems.food,
                toys: state.shopItems.toys
            }
        }
    }
})

// 初始化游戏
store.dispatch('initGame')

export default store
